//
//  ProfileEditor.swift
//  CatPomodoroTimer
//
//  Created by Xuri Li on 2024/8/13.
//

import SwiftUI

struct ProfileEditor: View {
    @Environment(\.presentationMode) var presentationMode // 环境变量用于控制视图的返回
    @Binding var profile: Profile
    private let profileManager = ProfileManager()
    
    @State private var originalProfile: Profile
    var onChangeDuration: (() -> Void)?
    
    init(profile: Binding<Profile>, onChangeDuration: (() -> Void)? = nil) {
        _profile = profile
        _originalProfile = State(initialValue: profile.wrappedValue)
        self.onChangeDuration = onChangeDuration
    }
    
    var body: some View {
        List {
            Picker("专注时长", selection: $profile.focusDuration) {
                ForEach(Profile.FocusDurationLevel.allCases) { level in
                    Text("\(level.rawValue)分钟")
                        .font(.subheadline)
                        .tag(level)
                }
            }
            .font(.subheadline)
            Toggle(isOn: $profile.isShowCat, label: {
                Text("猫咪陪伴")
                    .font(.subheadline)
            })
            Toggle(isOn: $profile.isShowCount, label: {
                Text("显示当日专注次数")
                    .font(.subheadline)
            })
            Toggle(isOn: $profile.vibrationFeedback, label: {
                Text("结束时震动反馈")
                    .font(.subheadline)
            })
//            HStack {
//                Text("历史记录")
//                Spacer()
//                Image(systemName: "chevron.right")
//            }
        }
        .navigationTitle("设置")
        .navigationBarBackButtonHidden(true) // 隐藏默认的返回按钮
        .toolbar {
            ToolbarItem(placement: .topBarLeading) {
                Button(action: {
                    if profile != originalProfile {
                        profileManager.saveProfile(profile)
                        if profile.focusDuration != originalProfile.focusDuration {
                            onChangeDuration?()
                        }
                    }
                    presentationMode.wrappedValue.dismiss()
                }, label: {
                    Image(systemName: "chevron.left")
                        .font(.title2)
                        .foregroundColor(.primary)
                })
            }
        }
    }
}

#Preview {
    ProfileEditor(profile: .constant(.default))
}
